#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/8/15 17:21
# @Author  : youfeng
import random
import time

import requests

from enum.proxy_key import ProxyKey
from ext.proxy_base import ProxyBase

# 标注类名
__CLASS__ = "ProxyKuai"
# 标注是否使用当前代理
__USED__ = True


class ProxyKuai(ProxyBase):
    # 代理唯一标识
    __TAG__ = "kuai"

    __KUAIPROXY_API = "https://dps.kdlapi.com/api/getdps/?orderid=993266411770523&num=500&pt=1&f_et=1&sep=2"
    __KUAIPROXY_AUTH = {"username": "youfeng", "password": "s41gqage"}

    def __init__(self, log):
        super(ProxyKuai, self).__int__(log=log)

    def get_proxy_tag(self):
        return self.__TAG__

    def __parse_proxy_text(self, text):
        try:
            ip, last_time = text.split(",")
            # 添加最大生存时间过滤，防止IP一直被持有而导致大量使用被封禁
            if int(last_time) > self._PROXY_MAX_TTL:
                last_time = self._PROXY_MAX_TTL
            expire_time = int(time.time()) + int(last_time)
            return ip, expire_time
        except Exception as e:
            self.log.error("解析快代理失败: text = {}".format(text))
            self.log.exception(e)
        return None, None

    # 返回代理
    def get_proxy_list(self):

        username = self.__KUAIPROXY_AUTH["username"]
        password = self.__KUAIPROXY_AUTH["password"]

        for _ in xrange(3):
            proxy_list = []
            proxy_set = set()
            try:
                r = requests.get(self.__KUAIPROXY_API, timeout=10)
                if r is None or r.status_code != 200:
                    self.log.error("更新快代理网络异常...")
                    time.sleep(random.randint(1, 3))
                    continue

                line_list = r.text.strip().split('\n')
                for line in line_list:
                    line = line.strip().strip("\r").strip("\n")
                    if len(line) <= 0:
                        continue

                    ip, expire_time = self.__parse_proxy_text(line)
                    if ip is None:
                        continue

                    if ip in proxy_set:
                        continue

                    proxy_set.add(ip)

                    proxy = 'http://{}:{}@{}'.format(username, password, ip)

                    proxy_list.append({
                        ProxyKey.EXPIRE_TIME_KEY: expire_time,
                        ProxyKey.PROXY_KEY: proxy
                    })

                self.log.info('从快代理官网更新代理成功: length = {}'.format(len(proxy_list)))
                return proxy_list
            except Exception as e:
                self.log.error('访问快代理链接异常: ')
                self.log.exception(e)
                time.sleep(random.randint(1, 3))
        return []
